package com.letme.store.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.letme.common.annotation.DataScope;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.letme.common.core.domain.TreeSelect;
import com.letme.common.utils.SecurityUtils;
import com.letme.common.utils.StringUtils;
import com.letme.common.core.domain.entity.MallClassification;
import com.letme.store.domain.vo.ClassificationVO;
import com.letme.store.mapper.MallClassificationMapper;
import com.letme.store.service.IMallClassificationService;
import org.springframework.stereotype.Service;

/**
 * 产品分类Service业务层处理
 *
 * @author lock
 * @date 2024-12-17
 */
@Service
public class MallClassificationServiceImpl extends ServiceImpl<MallClassificationMapper, MallClassification> implements IMallClassificationService
{

    /**
     * 查询产品分类列表
     *
     * @param deptId 部门编号
     * @return 产品分类集合
     */
    @Override
    public List<ClassificationVO> selectClassificationListByDeptId(Long deptId) {
        List<MallClassification> list = this.baseMapper.selectList(new LambdaQueryWrapper<MallClassification>()
                .eq(MallClassification::getDeptId,deptId)
                .eq(MallClassification::getDelFlag,0));
        List<MallClassification> deptTrees = buildClassificationTree(list);
        return deptTrees.stream().map(ClassificationVO::new).collect(Collectors.toList());
    }

    @Override
    @DataScope(deptAlias = "bc")
    public List<TreeSelect> selectMallClassificationTreeList(MallClassification classification) {
        List<MallClassification> list = this.baseMapper.selectMallClassificationList(classification);
        return buildClassificationTreeSelect(list);
    }

    /**
     * 查询产品分类列表
     *
     * @param businessClassification 产品分类
     * @return 产品分类
     */
    @Override
    @DataScope(deptAlias = "bc")
    public List<MallClassification> selectMallClassificationList(MallClassification businessClassification)
    {
        return this.baseMapper.selectMallClassificationList(businessClassification);
    }

    /**
     * 获取产品分类详细信息
     * @param classId
     * @return 产品分类对象
     */
    public MallClassification selectMallClassificationByClassId(Long classId)
    {
        return this.getOne(new LambdaQueryWrapper<MallClassification>().select().eq(MallClassification::getClassId,classId).eq(MallClassification::getDelFlag,0));
    }



    /**
     * 新增产品分类
     *
     * @param mallClassification 产品分类
     * @return 结果
     */
    @Override
    public Boolean insertMallClassification(MallClassification mallClassification)
    {
        //获取当前的用户登录名
        String userName = SecurityUtils.getUsername();
        if(StringUtils.isNotEmpty(userName)){
            mallClassification.setCreateBy(userName);
            mallClassification.setUpdateBy(userName);
        }
        mallClassification.setDelFlag(0);
        mallClassification.setCreateTime(new Date());
        mallClassification.setUpdateTime(new Date());
        int rows = this.baseMapper.insert(mallClassification);
        return rows > 0;
    }

    /**
     * 修改产品分类
     *
     * @param mallClassification 产品分类
     * @return 结果
     */
    @Override
    public Boolean updateMallClassification(MallClassification mallClassification)
    {
        //获取当前的用户登录名
        String userName = SecurityUtils.getUsername();
        if(StringUtils.isNotEmpty(userName)){
            mallClassification.setUpdateBy(userName);
        }
        mallClassification.setUpdateTime(new Date());
        int rows = this.baseMapper.update(mallClassification,
                new LambdaQueryWrapper<MallClassification>().eq(MallClassification::getClassId, mallClassification.getClassId()));
        return rows > 0;
    }

    /**
     * 删除产品分类信息
     * 逻辑删除，实际还存在
     * @param classIds
     * @return
     */
    @Override
    public Boolean fakeDelMallClassificationByClassIds(Long[] classIds){
        MallClassification businessClassification = new MallClassification();
        businessClassification.setDelFlag(1);
        //获取当前的用户登录名
        String userName = SecurityUtils.getUsername();
        if(StringUtils.isNotEmpty(userName)){
            businessClassification.setUpdateBy(userName);
        }
        businessClassification.setUpdateTime(new Date());
        int rows = 0;
        for (Long id:classIds) {
            rows += this.baseMapper.update(businessClassification,
                    new LambdaQueryWrapper<MallClassification>().eq(MallClassification::getClassId, id));
        }
        return rows > 0;
    }

    /**
     * 删除产品分类信息
     * 真删除，删除后数据库不存在
     * @param classIds
     * @return
     */
    public Boolean realDelMallClassificationByClassIds(Long[] classIds){
        int rows = 0;
        for (Long id:classIds) {
            rows += this.baseMapper.delete(new LambdaQueryWrapper<MallClassification>().eq(MallClassification::getClassId,id));
        }
        return rows > 0;
    }


    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 产品分类列表
     * @return 下拉树结构列表
     */
    public List<TreeSelect> buildClassificationTreeSelect(List<MallClassification> depts)
    {
        List<MallClassification> deptTrees = buildClassificationTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param classifications 产品分类列表
     * @return 树结构列表
     */
    public List<MallClassification> buildClassificationTree(List<MallClassification> classifications)
    {
        List<MallClassification> returnList = new ArrayList<>();
        List<Long> tempList = classifications.stream().map(MallClassification::getClassId).collect(Collectors.toList());
        for (MallClassification classification : classifications)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(classification.getParentId()))
            {
                recursionFn(classifications, classification);
                returnList.add(classification);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = classifications;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<MallClassification> list, MallClassification t)
    {
        // 得到子节点列表
        List<MallClassification> childList = getChildList(list, t);
        t.setChildren(childList);
        for (MallClassification tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<MallClassification> getChildList(List<MallClassification> list, MallClassification t)
    {
        List<MallClassification> tlist = new ArrayList<>();
        Iterator<MallClassification> it = list.iterator();
        while (it.hasNext())
        {
            MallClassification n = (MallClassification) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getClassId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<MallClassification> list, MallClassification t)
    {
        return getChildList(list, t).size() > 0;
    }
}
